Loops

The Increment and Decrement Operators

number++;
number--;
++number;
--number;

The while loop

while (condition)
{
    // statements;
}

Using the while Loop for Input Validation

System.out.print("Enter a number in the range of 1 through 100: ");
number = keyboard.nextInt();
// Validate the input.
while (number < 1 || number > 100)
{
    System.out.println("That number is invalid.");
    System.out.print("Enter a number in the range of 1 through 100: ");
    number = keyboard.nextInt();
}

Mixing Calls to nextLine with Calls to Other Scanner Methods

String’s nextInt, nextDouble and next methods don’t consume the newline character, causing the newline to be consumed by whatever reads System.in next.

E.g.,

Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Enter your city: ");
String city = scanner.nextLine();
System.out.println("Hi " + name + ", your age is " + age + " and your city is " + city);

Fix:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.println("Enter your city: ");
String city = scanner.nextLine();
System.out.println("Hi " + name + ", your age is " + age + " and your city is " + city);

The do-while Loop

do
{
    // statements;
}
while (condition);

The for Loop

for (initialization; test; update)
{
    // statement
}
  1. Perform initialization expression (done only once)
  2. Evaluate the test expression. If it is false, terminate the loop
  3. Execute the body of the loop
  4. Perform update expression, then go back to step 2

Note: The for loop is a pre-test loop

Two Categories of Loops:

Running Totals and Sentinel Values

double runningTotalSales = 0.0; // Accumulator (Running Total)
double sales = 0.0;
while (sales != -1) // Sentinel value
{
    totalSales += sales;
    sales = scanner.nextDouble();
}

Nested Loops

The break and continue Statements

Important: break and continue bypass normal mechanisms and can make code hard to read & maintain—use only when needed

Deciding Which Loop to Use

while:

do-while

for:

Generating Random Numbers with the Random class

import java.util.Random;
Random randomNumbers = new Random();